package cn.yunhe.crm.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class SessionBindingLisenter implements HttpSessionBindingListener {
	
	public String username;
	public HttpSession ses;
	public SessionBindingLisenter(String username, HttpSession ses) {
		this.username = username;
		this.ses = ses;
	}

	
	//向session绑定数据时触发
	public void valueBound(HttpSessionBindingEvent event) {
		
		System.out.println("向session绑定数据");
		 HttpSession session = event.getSession();
		 
	     ServletContext application = session.getServletContext();   
	  
	    // 把用户放入在线列表 
	    Map map=(Map) application.getAttribute("usermap");   
	    // 第一次使用前，需要初始化   
	    if (map == null) {   
	         map=new HashMap();   
	         application.setAttribute("usermap", map);   
	     }   
	     map.put(this.username,ses);   
	}
	
	
	//session取消绑定时触发
	public void valueUnbound(HttpSessionBindingEvent event) {
		//System.out.println("session解除绑定");
		HttpSession session = event.getSession(); 
		ServletContext application = session.getServletContext(); 
		// 从在线列表中删除用户名 
		Map map=(Map) application.getAttribute("usermap");
		HttpSession ses=(HttpSession) map.get(this.username);
		try {
			session.getAttribute("user");
			if(ses.getId()!=session.getId()){
				map.remove(this.username);
			} 
		} catch (Exception e) {
			map.remove(this.username);
		}

		 
		System.out.println(this.username + "退出。");
	}

}
